package com.aaa.springboot.commons.exception;


import com.aaa.springboot.commons.lang.Result;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalException {




    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public  Result inter(InternalAuthenticationServiceException e){
        e.printStackTrace();
        return  Result.fail(500,e.getMessage());
    }


    /**
     * 我的异常
     *
     * @param exception 异常
     * @return {@link Result}
     */
    @ExceptionHandler(MyException.class)
    public Result  myException(MyException exception){
        exception.printStackTrace();
        return  Result.fail(exception.getCode(),exception.getMsg());


    }



    /**
     * 方法异常
     *
     * @param method 方法
     * @return {@link Result}
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result methodException(MethodArgumentNotValidException method)
    {

        BindingResult bindingResult = method.getBindingResult();

        List<ObjectError> allErrors = bindingResult.getAllErrors();
        ObjectError objectError = allErrors.stream().findFirst().get();
        return  Result.fail(410,"非法参数",objectError);
    }


    /**
     * 全局异常
     *
     * @param e e
     * @return {@link Result}
     */
    @ExceptionHandler(value = {Exception.class})
    public Result globalException(Exception e){


        return  Result.fail(500,e.getMessage());

    }
}
